#include "clientgui.h"
#include "ui_clientgui.h"
#include <QDateTime>
#include <QUuid>
#include "qcustomplot/qcustomplot.h"

#define TEXT_COLOR_RED(STRING)         "<font color=red>" STRING "</font>" "<font color=black> </font>"
ClientGui::ClientGui(QWidget *parent) :
  QMainWindow(parent),
  ui(new Ui::ClientGui)
{
  ui->setupUi(this);
  opc = 0;
  m_upperLimmit = 1000;
  m_lowwerLimmit = 0;
  m_debugInfoOnOff = false;
  for(int i=0;i<6;i++){
      QString uuid = QUuid::createUuid().toString();

      qDebug()<<  uuid.mid(1,uuid.length()-2);
    }

  // 屏蔽按钮
//  ui->pushButton->setVisible(false);
//  ui->lineEdit->setVisible(false);
//  ui->pushButton_3->setVisible(false);
  // generate some data:
//  QVector<double> x(10001), y(10001), y2(10001); // initialize with entries 0..10001
//  for (int i=0; i<10001; ++i)
//  {
//    x[i] = i/50.0 - 1;
//    y[i] = x[i]*x[i]; // let's plot a quadratic function
//    y2[i] = x[i];
//  }

  // create graph and assign data to it:
  ui->customPlot->addGraph();
  //ui->customPlot->graph(0)->setData(x, y);
  // give the axes some labels:
  ui->customPlot->yAxis->setLabel("读取值");

  // 设置x轴为时间
  QSharedPointer<QCPAxisTickerTime> timeTicker(new QCPAxisTickerTime);
  timeTicker->setTimeFormat("%h:%m:%s");
  //设置x轴有20个坐标，这个没用，要另一个策略函数配合
  //timeTicker->setTickCount(20);

  ui->customPlot->xAxis->setTicker(timeTicker);
  ui->customPlot->xAxis->setTickLabels(true);

  //设置x轴名称
  ui->customPlot->xAxis->setLabel("时间");
  int nowtime = QTime::currentTime().msecsSinceStartOfDay(); // 当前时间总的毫秒数
  ui->customPlot->xAxis->setTickLabelRotation(45);

  ui->customPlot->xAxis->setRange((nowtime-30000)*0.001, nowtime*0.001);
  ui->customPlot->yAxis->setRange(0, 1000);

  ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);

//  历史曲线初始化
  ui->widget_historicChart->addGraph();
  //ui->widget_historicChart->setLineStyle(QCPGraph::lsNone);
  ui->widget_historicChart->yAxis->setLabel("历史值");
  // 设置x轴为时间
  ui->widget_historicChart->xAxis->setTicker(timeTicker);
  ui->widget_historicChart->xAxis->setTickLabels(true);
  //设置x轴名称
  ui->widget_historicChart->xAxis->setLabel("时间");
  ui->widget_historicChart->xAxis->setTickLabelRotation(45);

  ui->widget_historicChart->xAxis->setRange((nowtime-30000)*0.001, nowtime*0.001);
  ui->widget_historicChart->yAxis->setRange(0, 1000);

  ui->widget_historicChart->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom | QCP::iSelectPlottables);



}

ClientGui::~ClientGui()
{
  if(opc){
      opc->DisConnect();
      opc->deleteLater();
    }
  delete ui;
}
void ClientGui::sl_OnDataChange(OPCHANDLE hGroup,  DWORD dwCount, OPCHANDLE *phClientItems, VARIANT *pvValues, WORD *pwQualities, FILETIME *pftTimeStamps, HRESULT *pErrors)
{
  for (DWORD i = 0; i < dwCount; i++) {
      qDebug()<<"---from gui:"
          <<hGroup
          <<dwCount
          <<phClientItems[i]
          <<opc->VariantString(pvValues[i])
          <<opc->QualityString(pwQualities[i])
          <<QString::number(pftTimeStamps[i].dwLowDateTime)
          <<pErrors[i];

      QString qstr = QString::number(hGroup, 10) +" "+
              QString::number(dwCount, 10) + " "+
              QString::number(phClientItems[i]) + " " +
              opc->VariantString(pvValues[i]) + " " +
              opc->QualityString(pwQualities[i]) + " " +
              QString::number(pftTimeStamps[i].dwLowDateTime);
      if (pvValues[i].fltVal>m_upperLimmit || pvValues[i].fltVal<m_lowwerLimmit)
      {
          ui->textBrowser_debug->append(qstr+"读取值异常");
      }
      else if(m_debugInfoOnOff == true)
      {
          ui->textBrowser_debug->append(qstr);
      }
      int nowtime = QTime::currentTime().msecsSinceStartOfDay(); // 当前时间总的毫秒数
      ui->customPlot->graph()->addData(nowtime*0.001, pvValues[i].fltVal);
      ui->customPlot->xAxis->setRange((nowtime-30000)*0.001, nowtime*0.001);
      ui->customPlot->replot();

      //插入数据
      if(!m_sql_query.exec("INSERT INTO item VALUES('"+ui->lineEdit_addItem->text()+"', "+
                           QString::number(pvValues[i].fltVal)+", '" +
                           QTime::currentTime().toString() + "')"))
      {
          qDebug() << m_sql_query.lastError();
      }
      else
      {
          qDebug() << "inserted success!";
      }
    }
}


/* 连接服务器按钮槽 */
void ClientGui::on_btn_startopc_clicked()
{
  if(!opc)
  {
      opc = new OPCClient();
  }
  if(!opc->isConnected())
  {
      QString serverName = "KEPware.KEPServerEx.V4";
      bool result =  opc->Connect(serverName);
      if(result==S_OK)
      {
          qDebug()<< "连接成功";
          ui->textBrowser_debug->append(serverName + "连接成功");
          QString groupName = "MPI";
          if(opc->AddGroup(groupName,1000)==S_OK){
              qDebug()<< "分组添加成功";

              connect(opc->m_COPCTransaction,SIGNAL(sg_OnDataChange(OPCHANDLE,DWORD,OPCHANDLE*,VARIANT*,WORD*,FILETIME*,HRESULT*)),this,SLOT(sl_OnDataChange(OPCHANDLE,DWORD,OPCHANDLE*,VARIANT*,WORD*,FILETIME*,HRESULT*)));
            }else{
              qDebug()<< "装载失败";
            }
       }
   }

}

void ClientGui::on_pushButton_clicked()
{
    if(opc){
       qDebug()<<"删除所有项:"<< opc->RemoveAllItems();
       qDebug()<<opc->items->count();

      }
}

/*
    添加项的按钮槽函数
*/
void ClientGui::on_pushButton_addItem_clicked()
{
  if(!opc) return;
  QStringList inames;
  QString qstr = ui->lineEdit_addItem->text();
  inames.append(qstr);
  QStringList r_inames= opc->AddItems(inames);
  if(r_inames.count()>0){
      qDebug()<<"添加项目监视成功。" ;
      ui->textBrowser_debug->append("添加项监视成功:" + qstr);
//     for(int i=0;i<opc->items->count();i++){
//          qDebug()<<"读取指定项目值：" ;
//          if(opc->ReadItem(opc->items->value(i))){
//              qDebug()<< opc->items->value(i)->hServerHandle<<opc->items->value(i)->hClientHandle<<opc->QualityString(opc->items->value(i)->quality)<<opc->VariantString(opc->items->value(i)->value);
//            }
//       }
    }else{
      qDebug()<<"添加项目监视失败。";
    }
}


void ClientGui::on_pushButton_4_clicked()
{
    if(opc){
        opc->RemoveItems(QStringList()<<ui->lineEdit_removeItem->text());
      }
}

/*
    函数功能：设置报警上下限对应槽

*/
void ClientGui::on_pushButton_setLimmit_clicked()
{
    m_upperLimmit = ui->lineEdit_upperLimmit->text().toFloat();
    m_lowwerLimmit = ui->lineEdit_lowwerLimmit->text().toFloat();
    ui->textBrowser_debug->append("设置上限:"+QString::number(m_upperLimmit) + " 下限:" + QString::number(m_lowwerLimmit) + " 成功");

}

void ClientGui::on_radioButton_debugInfoOnOff_toggled(bool checked)
{
    if(checked == true)
    {
        m_debugInfoOnOff = true;
        ui->textBrowser_debug->append("打印信息开");
    }
    else
    {
        m_debugInfoOnOff = false;
        ui->textBrowser_debug->append("打印信息关");
    }
}
/*
    历史曲线显示

*/
void ClientGui::on_pushButton_confirmTime_clicked()
{
    int nowtime = QTime::currentTime().msecsSinceStartOfDay(); // 当前时间总的毫秒数
//    ui->widget_historicChart->graph()->addData(nowtime*0.001, 123);
    ui->widget_historicChart->xAxis->setRange(ui->dateTimeEdit_historicStartTime->time().msecsSinceStartOfDay()*0.001,
                                              ui->dateTimeEdit_historicEndTime->time().msecsSinceStartOfDay()*0.001);
    //qDebug()<<ui->dateTimeEdit_historicStartTime->time();
    m_sql_query.exec("select * from item");
    if (!m_sql_query.exec())
    {
        qDebug()<<m_sql_query.lastError();
        ui->textBrowser_debug->append(m_sql_query.lastError().text());
    }
    else
    {
        qDebug()<<"读取历史数据成功";
        ui->textBrowser_debug->append("读取历史数据成功");
        while(m_sql_query.next())
        {
            if (m_sql_query.value(0) == ui->lineEdit_addItem->text() &&
                    m_sql_query.value(2)>ui->dateTimeEdit_historicStartTime->text()&&
                    m_sql_query.value(2)<ui->dateTimeEdit_historicEndTime->text())
            {
                //QTime tm=QTime::fromString(str,"hh:mm:ss");
                qDebug()<<m_sql_query.value(0).toString()<<m_sql_query.value(1).toDouble()<<
                          m_sql_query.value(2);
                QTime qtime = QTime::fromString(m_sql_query.value(2).toString(),"hh:mm:ss");
                ui->widget_historicChart->graph()->addData(qtime.msecsSinceStartOfDay()*0.001,
                                                           m_sql_query.value(1).toDouble());
                //ui->customPlot->graph()->addData(nowtime*0.001, pvValues[i].fltVal);
                ui->widget_historicChart->replot();
            }
        }
    }

    ui->widget_historicChart->replot();
}


/*
     写服务器按钮槽
*/

void ClientGui::on_pushButton_write2Server_clicked()
{
    if (opc->isWriteAble)
    {
        QString tagName = "Channel1.Device1.test3";
        QString value = "35";
        bool bRet = opc->WriteValue(tagName, value);
        qDebug()<<"WriteValue's result = "<<bRet;
    }

}
